import pygame
import os

from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from alien import Alien
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard


def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    
    # 初始化音效系统
    pygame.mixer.init()
    # 加载背景音乐（不立即播放）
    bg_music_path = os.path.join(os.path.dirname(__file__), 'sound', 'bg_music2.mp3')
    pygame.mixer.music.load(bg_music_path)
    pygame.mixer.music.set_volume(ai_settings.music_volume)
    
    # 加载音效
    sounds = {
        'ship_shot': pygame.mixer.Sound(os.path.join(os.path.dirname(__file__), 'sound', 'ship_shot.wav')),
        'explosion': pygame.mixer.Sound(os.path.join(os.path.dirname(__file__), 'sound', 'explosion.wav'))
    }
    # 设置音效音量
    for sound in sounds.values():
        sound.set_volume(ai_settings.sound_volume)

    # 创建play按钮
    play_button = Button(ai_settings, screen, "开始")
    # 创建一个用于存储游戏统计信息的实例,并创建记仇牌子
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    # 创建一艘飞船
    ship = Ship(ai_settings, screen)
    # 创建一个用于存储子弹的编组
    bullets = Group()
    # 创建一个外星人实例
    aliens = Group()
    # 创建外星人群
    gf.create_fleet(ai_settings, screen, ship, aliens)
    # 开始游戏的主循环
    while True:
        # 监视键盘和鼠标事件
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, sounds)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets, sounds)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)


if __name__ == '__main__':
    run_game()
